package com.tencent.shadow.sample.host.http.RetrofitUtil;

import org.apache.http.conn.ssl.SSLSocketFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionPool;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Created by jsrgc on 2017/5/25.
 */

public abstract class CallManager {

    private static final int DEFAULT_MAXIDLE_CONNECTIONS = 5;
    private static final long DEFAULT_KEEP_ALIVEDURATION = 8;
    private final static int CONNECT_TIMEOUT = 30;

    private final static int READ_TIMEOUT = 30;

    private final static int WRITE_TIMEOUT = 20;

    private static ConnectionPool connectionPool
            = new ConnectionPool(DEFAULT_MAXIDLE_CONNECTIONS, DEFAULT_KEEP_ALIVEDURATION, TimeUnit.SECONDS);

    private static Map<String, Object> map = new HashMap<String, Object>();
    private OkHttpClient mOkHttpClient;

    private OkHttpClient getOkHttpClient() {

        if (mOkHttpClient == null) {
            ConnectionPool connectionPool
                    = new ConnectionPool(DEFAULT_MAXIDLE_CONNECTIONS, DEFAULT_KEEP_ALIVEDURATION, TimeUnit.SECONDS);
            OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder().connectionPool(connectionPool)
                    //SSL证书
                    .sslSocketFactory(TrustManager.getUnsafeOkHttpClient())
                    .hostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                    //失败重连
                    .retryOnConnectionFailure(true);
            if (getInterceptor() != null) {
                okHttpClientBuilder.addInterceptor(getInterceptor());
            }
            mOkHttpClient = okHttpClientBuilder.build();
        }
        return mOkHttpClient;
    }

    public <S> S createService(Class<S> serviceClass, String BaseUrl, Converter.Factory factory) {

        if (map.get(BaseUrl + serviceClass.getName()) != null) {
            return (S) map.get(serviceClass.getName());
        }
        Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BaseUrl);
        if (factory != null) {
            builder.addConverterFactory(factory);
        }
        Retrofit retrofit = builder.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(getOkHttpClient()).build();
        S service = retrofit.create(serviceClass);
        map.put(BaseUrl + serviceClass.getName() + BaseUrl, service);
        return service;
    }

    protected abstract Interceptor getInterceptor();
}
